package com.pay.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pay.beans.ReturnContent;
import com.pay.common.util.PropertyUtil;
import com.pay.constants.MarketplanConstant;
import com.pay.constants.RetConstants;
import com.pay.constants.WeixinConstants;
import com.pay.dubbo.wx.WxServiceFacade;
import com.pay.entity.wx.WxCustRelation;
import com.pay.entity.wx.WxPayDetail;
import com.pay.entity.wx.WxPayTemplate;
import com.pay.enums.WxPayStatus;
import com.pay.mapper.wx.WxCustRelationMapper;
import com.pay.mapper.wx.WxPayDetailMapper;
import com.pay.mapper.wx.WxPayTemplateMapper;
import com.pay.service.AccessTokenService;
import com.pay.service.WxPayTemplateService;

@Service("wxPayTemplateService")
public class WxPayTemplateServiceImpl implements WxPayTemplateService {

	private Logger logger = LoggerFactory.getLogger(WxPayTemplateServiceImpl.class);

	@Resource
	private WxPayTemplateMapper wxPayTemplateMapper;
	@Resource
	private WxServiceFacade wxServiceFacade;
	@Resource
	private AccessTokenService accessTokenService;
	@Resource
	private WxPayDetailMapper wxPayDetailMapper;
	@Resource
	private WxCustRelationMapper wxCustRelationMapper;

	private static String paytemplate;
	static {
		PropertyUtil propertyUtil = PropertyUtil.getInstance("wxweb");
		paytemplate = propertyUtil.getProperty("weixin.redpack.pay.template");
	}

	@Override
	public void insert(WxPayTemplate wxPayTemplate) {
		wxPayTemplateMapper.insert(wxPayTemplate);
	}

	@Override
	public WxPayTemplate findTemplateByOutTradeNo(String outerAppId, String outerTradeNo) {
		return wxPayTemplateMapper.findTemplateByOutTradeNo(outerAppId, outerTradeNo);
	}

	@Override
	public WxPayTemplate findTemplateById(String wxPayTemplateId) {
		return wxPayTemplateMapper.findTemplateById(wxPayTemplateId);
	}

	@Override
	public void update(WxPayTemplate wxPayTemplate) {
		wxPayTemplateMapper.update(wxPayTemplate);
	}

	@Override
	public String sendPayTemplate(Map<String, String> param) {
		logger.info("WxPayTemplateServiceImpl/sendPayTemplate/param:{}", param);
		String code = RetConstants.SUCCESS;
		String msg = "";

//		String title = param.get("title");// 模板标题
		String outerAppId = param.get("outerAppId");//
		String outerTradeNo = param.get("outerTradeNo");// 订单号
		String outerOpenid = "";//友刷微信openid
		String amount = param.get("amount");// 金额
		String desc = param.get("desc");// 模板描述
		String url = param.get("url");// 详情地址
		String notifyURL = param.get("notifyURL");// 模板备注
		String customerNo = param.get("customerNo");// 商户编号
		
		try {
			WxCustRelation custRelation = wxCustRelationMapper.findByCustomerNo(customerNo);
			if (custRelation==null) {
				return JSON.toJSONString(new ReturnContent<Object>(MarketplanConstant.NOT_SUBSCRIBE_BINDING, "商户没有关注或绑定微信号"));
			}else{
				//已绑定
				outerOpenid= custRelation.getOpenid();
			}
			//跳转串拼url
			String payTemplateUrl  = new StringBuffer(url)
								.append("outerAppId=").append(outerAppId)
								.append("&outerOpenId=").append(outerOpenid)
								.append("&outerTradeNo=").append(outerTradeNo)
								.append("&customerNo=").append(customerNo)
								.append("&notifyURL=").append(notifyURL).toString();
			
			WxPayTemplate wxPayTemplate = wxPayTemplateMapper.findTemplateByOutTradeNo(outerAppId, outerTradeNo);
			logger.info("WxPayTemplateServiceImpl/sendPayTemplate/wxPayTemplate:{}", JSON.toJSONString(wxPayTemplate));
			if (wxPayTemplate == null) {
				Map<String, Object> map = new HashMap<>();
				map.put("touser", outerOpenid);
				map.put("template_id", paytemplate);
				map.put("topcolor", "#FF0000");
				map.put("url", payTemplateUrl);

				JSONObject contentObj = new JSONObject();
				JSONObject param1 = new JSONObject();
				JSONObject param2 = new JSONObject();
				JSONObject param3 = new JSONObject();
				JSONObject param4 = new JSONObject();
				JSONObject param5 = new JSONObject();

				param1.put("value", "恭喜您获得现金红包奖励");
				param1.put("color", "#FF0000");
				contentObj.put("first", param1);

				param2.put("value", desc);
				param2.put("color", "#000000");
				contentObj.put("keyword1", param2);

				String amountValue = amount + "元";
				param3.put("value", amountValue);
				param3.put("color", "#000000");
				contentObj.put("keyword2", param3);
				
				param4.put("value", "微信现金红包");
				param4.put("color", "#000000");
				contentObj.put("keyword3", param4);

				param5.put("value", "\n请点击详情进行领取。\n友刷感谢您的参与。\n");
				param5.put("color", "#000000");
				contentObj.put("remark", param5);

				map.put("data", contentObj);
				logger.info("WxPayTemplateServiceImpl/sendPayTemplate/data:{}", JSON.toJSONString(map));
				String result = wxServiceFacade.sendMessage(WeixinConstants.templateMessageUrl,
								accessTokenService.getAccessToken(), JSON.toJSONString(map));
				//String result = "{\"errcode\":0 ,\"msgid\":\""+System.currentTimeMillis()+"\"}";
				logger.info("WxPayTemplateServiceImpl/sendPayTemplate/result:{}", result);
				JSONObject obj = JSON.parseObject(result);
				int errcode = obj.getIntValue("errcode");
				if (0 == errcode) {
					String msgId = obj.getString("msgid");
					// 红包模板发送记录
					wxPayTemplate = new WxPayTemplate(outerAppId, outerTradeNo, outerOpenid, null, msgId, customerNo,
							new BigDecimal(amount), WxPayStatus.SENDSUCCESS.name(), null);
					wxPayTemplateMapper.insert(wxPayTemplate);
				} else {
					code = String.valueOf(errcode);
					msg = result;
				}
			} else {
				code = MarketplanConstant.ORDERNO_REPEAT_COMMIT;
				msg = "订单号已提交过，请更换后提交";
			}

			// 增加红包操作详情记录
			WxPayDetail wxPayDetail = new WxPayDetail(outerAppId, outerTradeNo, outerOpenid, customerNo,
					RetConstants.SUCCESS.equals(code) ? WxPayStatus.SENDSUCCESS.name() : WxPayStatus.SENDFAIL.name(),
					msg, null);
			wxPayDetailMapper.insert(wxPayDetail);

			return JSON.toJSONString(new ReturnContent<Object>(code, msg));
		} catch (Exception e) {
			logger.error("WxPayTemplateServiceImpl/sendPayTemplate/exceptioninfo:{}", e.getMessage());
			return JSON.toJSONString(new ReturnContent<Object>(RetConstants.SYSTEM_ERROR, RetConstants.SYSTEM_ERROR_MSG));
		}
	}

	@Override
	public List<WxPayTemplate> findTemByCustNoAndAppId(String custNo, String outerAppId) {
		return wxPayTemplateMapper.findTemByCustNoAndAppId(custNo, outerAppId);
	}

	@Override
	public List<WxPayTemplate> findWxPayTemplateByAppIdAndOpenId(String outerAppId, String openId) {
		return wxPayTemplateMapper.findTemplateByAppIdAndOpenId(outerAppId, openId);
	}


}
